//
//  HomeViewController.swift
//  许鲜
//
//  Created by hbl on 16/4/22.
//  Copyright © 2016年 hbl. All rights reserved.
//

import UIKit
import AFNetworking
import MJRefresh
import SVProgressHUD
class HomeViewController: UIViewController {
    var headHight = 125
    var cellIsOpen:Bool = false
    lazy var page:HeaderForCollection = {
        let page = HeaderForCollection()
        
        page.frame = CGRectMake(0, 0, mainW, 190)
        return page
    }()
    lazy var menu:MenuView = {
        let menu = MenuView()
        menu.delegate = self
        return menu
    }()
    lazy var collectionDataArray:[AnyObject] = [AnyObject]()
    let statLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    var mainCollect:UICollectionView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        setupCollect()
        //getCollectionData()
       mainCollect?.mj_header.beginRefreshing()
    }
    
    private func setupNav(){
        let left = NavLeftItme.leftItem()
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: left)
        
        let right = UIButton()
        right.bounds = CGRectMake(0, 0, 25, 25)
        right.addTarget(self, action: #selector(HomeViewController.rightOnClick), forControlEvents: UIControlEvents.TouchUpInside)
        right.setImage(UIImage(named: "60fenlei"), forState: UIControlState.Normal)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: right)
        
    }
    
    func rightOnClick(){
        
}
    
    private func setupCollect(){
        
        

        statLayout.minimumInteritemSpacing = 2
        //statLayout.itemSize = CGSizeMake(mainW/2 - 2.5, 200)
        
        mainCollect = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: statLayout)
        mainCollect?.backgroundColor = UIColor.whiteColor()
        view.addSubview(mainCollect!)
        mainCollect!.dataSource = self;
        mainCollect!.delegate = self
        
        mainCollect!.contentInset = UIEdgeInsetsMake(0, 0, 64, 0)
        mainCollect!.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 64, 0)
        mainCollect?.mj_header = BLGifHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.getCollectionData))
        
        
        mainCollect!.registerClass(MenuView.self, forCellWithReuseIdentifier: "menu")
        mainCollect!.registerNib(UINib.init(nibName: "HomeCollectionCell", bundle: nil), forCellWithReuseIdentifier: "cell")
        mainCollect?.registerClass(PageCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "head")
        
    }
    
     func getCollectionData(){
        let manager = AFHTTPSessionManager()
        manager.responseSerializer = AFHTTPResponseSerializer()
        var params = Dictionary<String,String>()
        params["locationid"] = "285"
        params["version"] = "5.5.0"
        
        manager.POST("http://mobile.xuxian.com/index/?__t=1461399939.225958&ver=2016040101", parameters: params, progress: nil, success: { (_, JSON) in
            do{
                let str = try NSJSONSerialization.JSONObjectWithData(JSON as! NSData, options: NSJSONReadingOptions.MutableContainers)["data"] as! Array<AnyObject>
               
                for i in 0..<str.count{

                    let temp = (str[i] as! Dictionary<String,AnyObject>)["goods"] as! Array<AnyObject>

                    let group = GoodsModel.mj_objectArrayWithKeyValuesArray(temp)
                   
                    self.collectionDataArray.append(group)
                    
                }
                self.mainCollect?.reloadData()
                self.mainCollect?.mj_header.endRefreshing()
                //print(str)
            }catch{
            
            }
            
            
            }) { (_, error) in
                print(error)
                SVProgressHUD.showErrorWithStatus("网络开小差了！！")
                self.mainCollect?.mj_header.endRefreshing()
        }
    
    }
    

    
    
    
}

extension HomeViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,MenuViewDelegate{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return collectionDataArray.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        var count = 0
        if section == 0 {
            count = 1
        }else{
           let temp = collectionDataArray[section - 1] as? Array<AnyObject>
            count = (temp?.count)!
        }
        return count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("menu", forIndexPath: indexPath) as! MenuView
            cell.delegate = self
            cell.isOpen = cellIsOpen
            return cell

        }else{
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! HomeCollectionCell
            let temp = collectionDataArray[indexPath.section - 1] as! Array<AnyObject>
            let goods = temp[indexPath.item] as! GoodsModel
            cell.goods = goods
            return cell
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        let pageView:PageCollectionReusableView?
        
        pageView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "head", forIndexPath: indexPath) as? PageCollectionReusableView
     
        return pageView!
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let returnSize:CGSize?
        if indexPath.section == 0 {
            returnSize = CGSizeMake(mainW,CGFloat(headHight) )
        }else{
           returnSize = CGSizeMake(mainW/2 - 2.5, 235)
        }
        return returnSize!
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return section == 0 ? CGSizeMake(mainW, 190) : CGSizeMake(mainW, 0)
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.section != 0 {
            let temp = collectionDataArray[indexPath.section - 1] as! Array<AnyObject>
            let goods = temp[indexPath.item] as! GoodsModel
            let modalVc = DetailsViewController()
            modalVc.modalPresentationStyle = UIModalPresentationStyle.Custom
            modalVc.goodsModel = goods
            presentViewController(modalVc, animated: true, completion: nil)
        }
    }
    
    func menuViewOnBottomClick(topView: MenuView, isOpen: Bool) {
        if !cellIsOpen{
            
                UIView.animateWithDuration(0.5) {
                self.cellIsOpen = !self.cellIsOpen
                self.headHight = 225
                    
                }

            }else{
    
                UIView.animateWithDuration(0.5) {
                self.cellIsOpen = !self.cellIsOpen
                self.headHight = 125
                    
                }
            }
        
        let index = NSIndexPath(forItem: 0, inSection: 0)
        let array = [index]
        self.mainCollect?.reloadItemsAtIndexPaths(array)
    }
    
}